package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.SysUser;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.SysUserMapper;
import com.zzyl.service.SysUserService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserVo login(LoginDto dto) {
        // 根据用户名查询数据库，看是否存在
        SysUser sysUser = sysUserMapper.selectByUsername(dto.getUsername());
        // 如果不存在，return
        if(sysUser == null){
            throw  new BaseException(BasicEnum.DATA_NOT_EXIST);
        }
        // 如果用户存在
        String passwordDB = sysUser.getPassword();
        //    匹配密码，BCrypt.checkpw
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), passwordDB);
        //       匹配失败，密码错误，return
        if(!checkpw){
            throw  new BaseException(BasicEnum.ORIGINAL_PASSWORD_ERROR);
        }
        //       匹配成功，生成token（JwtUtil.createJWT），return
        UserVo userVo = BeanUtil.copyProperties(sysUser, UserVo.class);
        Map<String,Object> map = new HashMap<>();
        map.put("id",sysUser.getId());
        map.put("username",sysUser.getUsername());
        userVo.setUserToken(JwtUtil.createJWT("itheima",600000,map));
        return userVo;
    }
}
